
const koa = require("koa")
const app = new koa()
const server = require("koa-static")
const send = require("koa-send")
const path = require("path")
const PORT = 9998

const router = require('koa-router');
let myRouter = new router();


myRouter.post('/a',function(ctx,next){

    // console.log('\n\nctx-->',ctx.req.headers);
    
    // ctx.set({
    //     'Cache-Control': 'max-age=60',
    //     // 'Expires':"100"
    // });
    ctx.body = {a:"hoholoving"}

    next()

})

myRouter.get('/cache',function(ctx,next){

    // console.log('\n\nctx-->',ctx.req.httpVersion);
    
    // ctx.set({
    //     'Cache-Control': 'max-age=60',
    //     // 'Expires':"100"
    // });
    ctx.body = {a:"hoholoving"}

    next()

})

function getExpires(date,last){

    var Date_value = new Date(date).getTime();
    var LastModified_value = new Date(last).getTime();

    var cacheTime = (Date_value - LastModified_value) / 10;

    var Expires_timestamp = Date_value + cacheTime;
    var Expires_value = new Date(Expires_timestamp);

    return  Expires_value.toString()
}


app

    .use(myRouter.routes())
    .use(async function(ctx,next){

        console.log('请求了一次',ctx.path);
        
        opts={}

        let done = false;

        opts.root=path.join(__dirname, "/src")
        
        ctx.set({
            // 'Cache-Control': 
            // 'Cache-Control': 'max-stale=0'+(ctx.path.indexOf("html")>-1?',max-age=0':""),
            // 'Cache-Control': 'max-stale=0',
            // 'Cache-Control': 'min-fresh=1820',
            'Cache-Control': 'max-age=10',
            // 'Cache-Control': 'no-store',
            'Expires':"Fri, 12 Aug 2018 16:40:14 GMT",
            // "ETag":"xojsjofajsdlkfe",
            // "Date":"Fri, 10 Aug 2018 9:03:14 GMT",
            // "Last-Modified":"Fri, 10 Aug 2018 9:02:14 GMT"
        });
        
        if (opts.index !== false){
            opts.index = opts.index || 'index.html';
        }
            
        if (ctx.method === 'HEAD' || ctx.method === 'GET') {

            var time=getExpires("Fri, 10 Aug 2018 9:35:14 GMT","Fri, 10 Aug 2018 9:30:14 GMT")

            try {
                done = await send(ctx, ctx.path, opts);
            } catch (err) {
                if (err.status !== 404) {
                    throw err;
                }
            }
        }
        
        if (!done) {
            await next();
        }

    })
    .use(myRouter.allowedMethods())
    
    // .use(server(path.join(__dirname, "/src")))
    .listen(PORT, () => {
        console.log("开启成功", `http://localhost:${PORT}/`)
    })